#include "swtimer.h"

void initSoftwareTimer(SoftwareTimer *timer, uint32_t interval, TimerType type, TimerCallback callback) {
    timer->interval = interval;
    timer->type = type;
    timer->callback = callback;
    timer->active = 0;
}

void startSoftwareTimer(SoftwareTimer *timer) {
    timer->startTick = HAL_GetTick();
    timer->active = 1;
}

void stopSoftwareTimer(SoftwareTimer *timer) {
    timer->active = 0;
}

int isSoftwareTimerTimeout(SoftwareTimer *timer) {
    if (!timer->active) {
        return 0;
    }
    uint32_t currentTick = HAL_GetTick();
    return (currentTick - timer->startTick >= timer->interval) ? 1 : 0;
}

void checkSoftwareTimers(SoftwareTimer *timers, int numTimers) {
    for (int i = 0; i < numTimers; i++) {
        SoftwareTimer *timer = &timers[i];
        if (timer->active) {
            uint32_t currentTick = HAL_GetTick();
            if (currentTick - timer->startTick >= timer->interval) {
                if (timer->callback) {
                    timer->callback();
                }
                if (timer->type == TIMER_TYPE_SINGLE) {
                    timer->active = 0; // 单次定时器，执行一次后停止
                } else {
                    timer->startTick = currentTick; // 周期性定时器，重置启动时tick值
                }
            }
        }
    }
}
